using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Performance;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.ServiceCollectionExtensions
{
    /// <summary>
    /// 高级性能优化服务注册扩展
    /// 提供租户级缓存、性能监控、查询优化等服务的注册
    /// </summary>
    public static partial class PerformanceServiceCollectionExtensions
    {
        /// <summary>
        /// 添加高级性能优化服务
        /// 包含租户缓存、性能监控、查询优化等功能
        /// </summary>
        public static IServiceCollection AddAdvancedPerformanceServices(this IServiceCollection services, IConfiguration configuration)
        {
            // 1. 添加租户级缓存服务
            services.AddScoped<ITenantCacheService, TenantCacheService>();
            
            // 2. 添加租户性能监控服务（改为Scoped，因为依赖ITenantContext）
            services.AddScoped<ITenantPerformanceService, TenantPerformanceService>();
            
            // 3. 添加查询优化服务
            services.AddScoped<IQueryOptimizationService, QueryOptimizationService>();
            
            // 4. 添加性能中间件和过滤器（不需要在这里注册中间件）
            // services.AddTransient<TenantPerformanceMiddleware>(); // 中间件不需要在这里注册
            services.AddTransient<QueryOptimizationFilter>();
            
            // 5. 配置性能监控选项
            services.Configure<PerformanceMonitoringOptions>(
                configuration.GetSection("Performance:Monitoring"));
            
            // 6. 配置缓存选项
            services.Configure<TenantCacheOptions>(
                configuration.GetSection("Performance:Cache"));
            
            // 7. 添加性能健康检查
            services.AddHealthChecks()
                .AddCheck<TenantPerformanceHealthCheck>("tenant_performance")
                .AddCheck<CacheHealthCheck>("tenant_cache");
            
            return services;
        }

        /// <summary>
        /// 添加性能监控中间件
        /// </summary>
        public static IServiceCollection AddPerformanceMonitoring(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<PerformanceMonitoringOptions>(options =>
            {
                configuration.GetSection("Performance:Monitoring").Bind(options);
                
                // 默认配置
                options.EnableRequestTracking ??= true;
                options.EnableQueryTracking ??= true;
                options.EnableCacheTracking ??= true;
                options.SlowQueryThreshold ??= TimeSpan.FromMilliseconds(1000);
                options.MaxRequestsPerMinute ??= 1000;
                options.DataRetentionPeriod ??= TimeSpan.FromHours(24);
            });
            
            return services;
        }

        /// <summary>
        /// 添加智能缓存配置
        /// </summary>
        public static IServiceCollection AddIntelligentCaching(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<TenantCacheOptions>(options =>
            {
                configuration.GetSection("Performance:Cache").Bind(options);
                
                // 默认配置
                options.DefaultExpiry ??= TimeSpan.FromMinutes(30);
                options.MemoryExpiry ??= TimeSpan.FromMinutes(5);
                options.MaxCacheSize ??= 100 * 1024 * 1024; // 100MB
                options.EnableDistributedCache ??= true;
                options.EnableMemoryCache ??= true;
                options.CacheWarmupEnabled ??= true;
            });
            
            return services;
        }
    }

    #region 配置选项

    /// <summary>
    /// 性能监控配置选项
    /// </summary>
    public class PerformanceMonitoringOptions
    {
        public bool? EnableRequestTracking { get; set; }
        public bool? EnableQueryTracking { get; set; }
        public bool? EnableCacheTracking { get; set; }
        public TimeSpan? SlowQueryThreshold { get; set; }
        public int? MaxRequestsPerMinute { get; set; }
        public TimeSpan? DataRetentionPeriod { get; set; }
        public List<string> ExcludedPaths { get; set; } = new();
        public Dictionary<string, TimeSpan> CustomThresholds { get; set; } = new();
    }

    /// <summary>
    /// 租户缓存配置选项
    /// </summary>
    public class TenantCacheOptions
    {
        public TimeSpan? DefaultExpiry { get; set; }
        public TimeSpan? MemoryExpiry { get; set; }
        public long? MaxCacheSize { get; set; }
        public bool? EnableDistributedCache { get; set; }
        public bool? EnableMemoryCache { get; set; }
        public bool? CacheWarmupEnabled { get; set; }
        public List<string> WarmupQueries { get; set; } = new();
        public Dictionary<string, TimeSpan> CustomExpiries { get; set; } = new();
    }

    #endregion

    #region 中间件和过滤器

    /// <summary>
    /// 租户性能监控中间件
    /// 自动跟踪所有HTTP请求的性能指标
    /// </summary>
    public class TenantPerformanceMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<TenantPerformanceMiddleware> _logger;
        private readonly PerformanceMonitoringOptions _options;

        public TenantPerformanceMiddleware(
            RequestDelegate next,
            ILogger<TenantPerformanceMiddleware> logger,
            Microsoft.Extensions.Options.IOptions<PerformanceMonitoringOptions> options)
        {
            _next = next;
            _logger = logger;
            _options = options.Value;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 检查是否启用请求跟踪
            if (_options.EnableRequestTracking != true)
            {
                await _next(context);
                return;
            }

            // 检查是否为排除路径
            var path = context.Request.Path.Value ?? "";
            if (_options.ExcludedPaths.Any(excluded => path.StartsWith(excluded, StringComparison.OrdinalIgnoreCase)))
            {
                await _next(context);
                return;
            }

            var tenantId = GetTenantIdFromContext(context);
            var operationName = GetOperationName(context);
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var success = true;

            try
            {
                await _next(context);
                
                // 检查响应状态码
                success = context.Response.StatusCode < 400;
            }
            catch (Exception ex)
            {
                success = false;
                _logger.LogError(ex, "请求处理异常: {Path} - 租户: {TenantId}", path, tenantId);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                
                // 从请求范围获取性能服务
                var performanceService = context.RequestServices.GetRequiredService<ITenantPerformanceService>();
                
                // 记录性能数据
                await performanceService.RecordRequestAsync(tenantId, operationName, stopwatch.Elapsed, success);
            }
        }

        private string GetTenantIdFromContext(HttpContext context)
        {
            // 尝试从多个位置获取租户ID
            if (context.Items.TryGetValue("TenantId", out var tenantId) && tenantId is string tid)
                return tid;

            if (context.Request.Headers.TryGetValue("X-Tenant-Id", out var headerTenantId))
                return headerTenantId.FirstOrDefault() ?? "unknown";

            return "unknown";
        }

        private string GetOperationName(HttpContext context)
        {
            var method = context.Request.Method;
            var path = context.Request.Path.Value ?? "";
            
            // 尝试获取控制器和动作名称
            var endpoint = context.GetEndpoint();
            if (endpoint?.DisplayName != null)
            {
                return endpoint.DisplayName;
            }
            
            return $"{method} {path}";
        }
    }

    /// <summary>
    /// 查询优化过滤器
    /// 自动应用查询优化和缓存
    /// </summary>
    public class QueryOptimizationFilter : Microsoft.AspNetCore.Mvc.Filters.IAsyncActionFilter
    {
        private readonly IQueryOptimizationService _queryOptimizationService;
        private readonly ILogger<QueryOptimizationFilter> _logger;

        public QueryOptimizationFilter(
            IQueryOptimizationService queryOptimizationService,
            ILogger<QueryOptimizationFilter> logger)
        {
            _queryOptimizationService = queryOptimizationService;
            _logger = logger;
        }

        public async Task OnActionExecutionAsync(
            Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context,
            Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            
            try
            {
                var result = await next();
                stopwatch.Stop();

                // 这里可以添加特定的查询优化逻辑
                // 例如，检查结果集大小，自动启用缓存等
                
                _logger.LogDebug("操作执行完成: {Action} ({Duration}ms)", 
                    context.ActionDescriptor.DisplayName, 
                    stopwatch.Elapsed.TotalMilliseconds);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                _logger.LogError(ex, "操作执行失败: {Action} ({Duration}ms)", 
                    context.ActionDescriptor.DisplayName, 
                    stopwatch.Elapsed.TotalMilliseconds);
                throw;
            }
        }
    }

    #endregion

    #region 健康检查

    /// <summary>
    /// 租户性能健康检查
    /// </summary>
    public class TenantPerformanceHealthCheck : Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck
    {
        private readonly ITenantPerformanceService _performanceService;
        private readonly ILogger<TenantPerformanceHealthCheck> _logger;

        public TenantPerformanceHealthCheck(
            ITenantPerformanceService performanceService,
            ILogger<TenantPerformanceHealthCheck> logger)
        {
            _performanceService = performanceService;
            _logger = logger;
        }

        public async Task<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult> CheckHealthAsync(
            Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context,
            CancellationToken cancellationToken = default)
        {
            try
            {
                // 这里可以添加具体的健康检查逻辑
                // 例如，检查性能指标是否正常，是否有过多的慢查询等
                
                var data = new Dictionary<string, object>
                {
                    ["timestamp"] = DateTime.UtcNow,
                    ["status"] = "healthy"
                };

                return await Task.FromResult( Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Healthy("租户性能监控正常", data));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "租户性能健康检查失败");
                return Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Unhealthy("租户性能监控异常", ex);
            }
        }
    }

    /// <summary>
    /// 缓存健康检查
    /// </summary>
    public class CacheHealthCheck : Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck
    {
        private readonly ITenantCacheService _cacheService;
        private readonly ILogger<CacheHealthCheck> _logger;

        public CacheHealthCheck(
            ITenantCacheService cacheService,
            ILogger<CacheHealthCheck> logger)
        {
            _cacheService = cacheService;
            _logger = logger;
        }

        public async Task<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult> CheckHealthAsync(
            Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context,
            CancellationToken cancellationToken = default)
        {
            try
            {
                // 执行缓存测试
                var testKey = $"health_check_{Guid.NewGuid()}";
                var testValue = DateTime.UtcNow.ToString();
                
                await _cacheService.SetAsync(testKey, testValue, TimeSpan.FromSeconds(30), "system");
                var retrievedValue = await _cacheService.GetAsync<string>(testKey, "system");
                
                if (retrievedValue == testValue)
                {
                    await _cacheService.RemoveAsync(testKey, "system");
                    
                    var data = new Dictionary<string, object>
                    {
                        ["timestamp"] = DateTime.UtcNow,
                        ["cache_test"] = "passed"
                    };

                    return Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Healthy("租户缓存服务正常", data);
                }
                else
                {
                    return Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Degraded("缓存读写不一致");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "缓存健康检查失败");
                return Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Unhealthy("缓存服务异常", ex);
            }
        }
    }

    #endregion
}

namespace JGSY.CMS.LowCode.Platform.Infrastructure.ServiceCollectionExtensions
{
    /// <summary>
    /// 高级性能优化服务注册扩展方法 - 带配置选项
    /// </summary>
    public static partial class PerformanceServiceCollectionExtensions
    {
        /// <summary>
        /// 添加高级性能优化系统 - 企业级性能解决方案
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureOptions">配置选项</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddAdvancedPerformanceOptimization(
            this IServiceCollection services, 
            Action<AdvancedPerformanceOptimizationOptions>? configureOptions = null)
        {
            var options = new AdvancedPerformanceOptimizationOptions();
            configureOptions?.Invoke(options);
            
            // 注册配置选项
            services.Configure<AdvancedPerformanceOptimizationOptions>(opt =>
            {
                opt.EnableCaching = options.EnableCaching;
                opt.EnablePerformanceMonitoring = options.EnablePerformanceMonitoring;
                opt.EnableQueryOptimization = options.EnableQueryOptimization;
                opt.CacheOptions = options.CacheOptions;
                opt.PerformanceOptions = options.PerformanceOptions;
                opt.QueryOptimizationOptions = options.QueryOptimizationOptions;
            });
            
            // 根据配置启用相应功能
            if (options.EnableCaching)
            {
                services.AddScoped<ITenantCacheService, TenantCacheService>();
            }
            
            if (options.EnablePerformanceMonitoring)
            {
                services.AddScoped<ITenantPerformanceService, TenantPerformanceService>(); // 改为Scoped
                // services.AddTransient<TenantPerformanceMiddleware>(); // 不需要在这里注册
            }
            
            if (options.EnableQueryOptimization)
            {
                services.AddScoped<IQueryOptimizationService, QueryOptimizationService>();
                services.AddTransient<QueryOptimizationFilter>();
            }
            
            // 添加健康检查
            var healthChecksBuilder = services.AddHealthChecks();
            
            if (options.EnablePerformanceMonitoring)
            {
                healthChecksBuilder.AddCheck<TenantPerformanceHealthCheck>("tenant_performance");
            }
            
            if (options.EnableCaching)
            {
                healthChecksBuilder.AddCheck<CacheHealthCheck>("tenant_cache");
            }
            
            return services;
        }
        
        /// <summary>
        /// 使用高级性能优化中间件
        /// </summary>
        /// <param name="app">应用程序构建器</param>
        /// <returns>应用程序构建器</returns>
        public static IApplicationBuilder UseAdvancedPerformanceOptimization(this IApplicationBuilder app)
        {
            // 使用性能监控中间件
            app.UseMiddleware<TenantPerformanceMiddleware>();
            
            return app;
        }
    }

    /// <summary>
    /// 高级性能优化配置选项
    /// </summary>
    public class AdvancedPerformanceOptimizationOptions
    {
        /// <summary>
        /// 启用缓存
        /// </summary>
        public bool EnableCaching { get; set; } = true;
        
        /// <summary>
        /// 启用性能监控
        /// </summary>
        public bool EnablePerformanceMonitoring { get; set; } = true;
        
        /// <summary>
        /// 启用查询优化
        /// </summary>
        public bool EnableQueryOptimization { get; set; } = true;
        
        /// <summary>
        /// 缓存选项
        /// </summary>
        public CacheOptionsConfig CacheOptions { get; set; } = new();
        
        /// <summary>
        /// 性能监控选项
        /// </summary>
        public PerformanceOptionsConfig PerformanceOptions { get; set; } = new();
        
        /// <summary>
        /// 查询优化选项
        /// </summary>
        public QueryOptimizationOptionsConfig QueryOptimizationOptions { get; set; } = new();
    }

    /// <summary>
    /// 缓存配置选项
    /// </summary>
    public class CacheOptionsConfig
    {
        /// <summary>
        /// 默认过期时间
        /// </summary>
        public TimeSpan DefaultExpiration { get; set; } = TimeSpan.FromMinutes(15);
        
        /// <summary>
        /// 启用分布式缓存
        /// </summary>
        public bool EnableDistributedCache { get; set; } = true;
        
        /// <summary>
        /// 启用内存缓存
        /// </summary>
        public bool EnableMemoryCache { get; set; } = true;
    }

    /// <summary>
    /// 性能监控配置选项
    /// </summary>
    public class PerformanceOptionsConfig
    {
        /// <summary>
        /// 告警阈值配置
        /// </summary>
        public AlertThresholdsConfig AlertThresholds { get; set; } = new();
        
        /// <summary>
        /// 启用实时告警
        /// </summary>
        public bool EnableRealTimeAlerts { get; set; } = true;
    }

    /// <summary>
    /// 告警阈值配置
    /// </summary>
    public class AlertThresholdsConfig
    {
        /// <summary>
        /// 慢查询阈值
        /// </summary>
        public TimeSpan SlowQueryThreshold { get; set; } = TimeSpan.FromSeconds(2);
        
        /// <summary>
        /// 高内存使用率阈值
        /// </summary>
        public double HighMemoryUsage { get; set; } = 0.8;
        
        /// <summary>
        /// 低缓存命中率阈值
        /// </summary>
        public double LowCacheHitRate { get; set; } = 0.7;
    }

    /// <summary>
    /// 查询优化配置选项
    /// </summary>
    public class QueryOptimizationOptionsConfig
    {
        /// <summary>
        /// 启用慢查询日志记录
        /// </summary>
        public bool EnableSlowQueryLogging { get; set; } = true;
        
        /// <summary>
        /// 最大缓存查询数量
        /// </summary>
        public int MaxCachedQueries { get; set; } = 1000;
        
        /// <summary>
        /// 查询缓存过期时间
        /// </summary>
        public TimeSpan QueryCacheExpiration { get; set; } = TimeSpan.FromMinutes(10);
    }
}
